package com.tzstcl.framework.handler;

import com.tzstcl.base.model.AjaxResult;
import com.tzstcl.framework.exception.RepeatSubmitException;
import com.tzstcl.framework.utils.ServletUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公司：天筑科技股份有限公司
 * 作者：zgq
 * 日期：2018年09月03日
 * 说明：全局异常处理类  ，将 Controller 层的异常和数据校验的异常进行统一处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限校验失败
     */
    @ExceptionHandler(AuthorizationException.class)
    public Object handleAuthorizationException(HttpServletRequest request, AuthorizationException e) {
        log.error("权限校验失败异常", e.getMessage(), e);
        String msg = "您未获取此操作权限，请联系管理员添加权限";
        return backFunc(request, msg);
    }

    /**
     * 参数校验失败处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Object handleMethodArgumentNotValidException(HttpServletRequest request, BindException e) {
        log.error("参数验证失败异常", e.getMessage(), e);
        //获取参数校验错误集合
        List<FieldError> fieldErrors = e.getFieldErrors();
        //格式化以提供友好的错误提示
        String data = String.format("参数校验错误（%s）：%s", fieldErrors.size(),
                fieldErrors.stream()
                        .map(FieldError::getDefaultMessage)
                        .collect(Collectors.joining(";")));
        String msg = data;
        return backFunc(request, msg);
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public Object handleMethodNotSupportedException(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
        log.error("请求方式不支持异常",e.getMessage(), e);
        String msg = "不支持' " + e.getMethod() + "'请求";
        return backFunc(request, msg);
    }
    /**
     * 重复提交异常
     */
    @ExceptionHandler({RepeatSubmitException.class})
    public Object handleRepeatSubmitException(HttpServletRequest request, RepeatSubmitException e) {
        log.error("重复提交异常:", e.getMessage(), e);
        String msg =   e.getMessage()  ;
        return backFunc(request, msg);
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Object notFount(HttpServletRequest request, RuntimeException e) {
        log.error("运行时异常:", e.getMessage(), e);
        String msg = "运行时异常" + e.getMessage();
        return backFunc(request, msg);
    }
    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Object handleException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("系统未知异常:", e.getMessage(), e);
        String msg = "服务器错误，请联系管理员";
        return backFunc(request, msg);
    }

    private Object backFunc(HttpServletRequest request, String msg) {
        //判断请求是否为Ajax请求
        if (ServletUtils.isAjaxRequest(request)) { //如果是的话，就直接返回错误信息
            return AjaxResult.error(msg);
        } else { //如果不是的话，就跳转到错误页面
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("msg", msg);
            modelAndView.setViewName("error"); //这里需要在templates文件夹下新建一个error.html文件用作错误页面
            return modelAndView;
        }
    }

}
